/* Copyright (c) 2011 Alexandre Défossez, Timothée Lacroix
 * This file is part of HINAPT.
 *
 * HINAPT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * HINAPT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HINAPT.  If not, see <http://www.gnu.org/licenses/>.
 */


#include "train.hpp"

using namespace fs;


void train(double f,double d,double ftarget,string file){

  vector<path> images;
  vector<Mat> validation,neg,pos;
  vector<int> trueVal;

  listFiles(images,initial_path()/"trainPic/faceValidate/");

  for(int i=0;i<(int)images.size();i++){
    validation.push_back(extract(images[i]));
    trueVal.push_back(1);
  }
  images.clear();
  listFiles(images,initial_path()/"trainPic/nonfaceValidate/");
  for(int i=0;i<(int)images.size();i++){
    validation.push_back(extract(images[i]));
    trueVal.push_back(-1);
  }

  printf("%d validation images loaded\n",(int)validation.size());

  double curF, curD;
  DetectorTh cascade;
  int level;
  ofstream vjDebug("debug/vj", ofstream::app);
  while(true){
    ifstream input(file.c_str());
    if (!cascade.load(input)){
      printf("LOADING FAILED\n");
      return;
    }
    input.close();

    level = cascade.size();

    system("./train.py");
    load(pos,neg);

    debugOut.open(("debug/adaboost_"+toString(level)).c_str(), ofstream::app);

    cascade.findFD(curF,curD,validation,trueVal);
    vjDebug << level << "," << curF << "," << curD << endl;

    if (curF<=ftarget){
      printf("It is finally over.\n");
      break;
    }

    new ClassifierTh(f*curF,d*curD,validation,trueVal,pos,neg,cascade);

    printf("-------------- Next Level -----------------\n");

    ofstream output(file.c_str());
    cascade.save(output);
    output.close();
  }
}
